package me.boot.auth.spring.service;

import cn.hutool.core.util.StrUtil;
import me.boot.auth.spring.AuthUtils;
import me.boot.auth.spring.model.SpringUser;
import me.boot.sys.entity.SysResource;
import me.boot.sys.entity.SysRole;
import me.boot.sys.entity.SysUser;
import me.boot.sys.service.SysResourceService;
import me.boot.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.List;

/**
 * File Name             :  CustomUserDetailsService
 *
 * @author :  sylar
 * @create :  2018/11/19
 * Description           :
 * Reviewed By           :
 * Reviewed On           :
 * Version History       :
 * Modified By           :
 * Modified Date         :
 * Comments              :
 * CopyRight             : COPYRIGHT(c) me.iot.com   All Rights Reserved
 * *******************************************************************************************
 */
@Component
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserService userService;

    @Autowired
    SysResourceService resourceService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public SpringUser getById(Long userId) {
        SysUser sysUser = userService.getById(userId);
        return AuthUtils.fromSysUser(sysUser);
    }

    @Override
    public SpringUser getByUsername(String username) {
        SysUser sysUser = userService.getByUsername(username);
        if (null == sysUser) {
            throw new UsernameNotFoundException(username);
        }
        return AuthUtils.fromSysUser(sysUser);
    }

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        return getByUsername(loginName);
    }

    @Override
    public List<SysRole> findByUrl(String requestUrl, String httpMethod) {
        boolean isGetMethod = StrUtil.equalsIgnoreCase(HttpMethod.GET.toString(), httpMethod);

        List<SysResource> resources = resourceService.findAllByOrderByUrlDesc();
        for (SysResource resource : resources) {
            String apiUrl = AuthUtils.trimResourceUrl(resource.getApiUri());
            if (StrUtil.isEmpty(apiUrl)) {
                continue;
            }
            if (isGetMethod) {
                apiUrl = apiUrl + "**";
            }

            if (antPathMatcher.matchStart(apiUrl, requestUrl)) {
                return resourceService.getRoles(resource.getId());
            }
        }
        return null;
    }

}
